package com.hitqz.robot.driver.schedule;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.hitqz.robot.driver.service.NettyChannelService;
import com.hitqz.robot.driver.util.SourceEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

/**
 * @author xupkun
 * @date 2024/11/26
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CheckAliveSchedule {


    public static String ip = "";

    @Scheduled(fixedDelay = 500)
    public void reconnect() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        long uptime = runtimeMXBean.getUptime();
        //String ip = NettyChannelService.ipAddress;
        //log.info("ip" + ip);
        if (uptime < 1000 * 60 ){
            return;
        }
        if (StrUtil.isBlank(ip)) {
            //log.info("未设置ip");
            return ;
        }
        if (!NetUtil.ping(ip,1000)) {
            NettyChannelService.connect(ip, null);
        } else {
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_MESSAGE_PUSH.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_MESSAGE_PUSH);
            }
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_NAV.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_NAV);
            }
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_OTHER.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_OTHER);
            }
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_STATUS.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_STATUS);
            }
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_CONTROLLER.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_CONTROLLER);
            }
            if (NettyChannelService.checkHasConnection(SourceEnum.ROBOT_CONFIG.getSource())) {
                NettyChannelService.connect(ip, SourceEnum.ROBOT_CONFIG);
            }

        }


    }


}
